import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/widgets.dart';
import 'package:ls_work/a_elder/models/elder_entity.dart';
import 'package:ls_work/a_elder/page/elder_search_page.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/food_menu_list.dart';
import 'package:ls_work/net/response/response_data.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/resources.dart';

class AddMealViewModel extends BaseViewModel {
  final ElderInfo? info;

  AddMealViewModel(BuildContext context, {this.info}) : super(context) {
    if (info != null) {
      older = info;
    }
  }

  ElderInfo? older;

  var mealTime = "";
  var timeRange = "";
  var timeRangeName = "";

  Future<void> selectOlder() async {
    older = await Go().push(ElderSearchPage(
      needBack: true,
      isSelected: false,
    ));
    notifyListeners();
  }

  var _formats = [yyyy, "-", mm, "-", dd, " ", HH, ":", nn, ":", ss];

  void selectMealTime() {
    DatePicker.showDateTimePicker(context, onConfirm: (date) {
      mealTime = formatDate(date!, _formats, LocaleType.zh);
      notifyListeners();
    });
  }

  void selectFoodType() {
    var items = [
      PickerDataWithIdModel(pickName: "早餐", pickId: "1"),
      PickerDataWithIdModel(pickName: "午餐", pickId: "2"),
      PickerDataWithIdModel(pickName: "晚餐", pickId: "3"),
    ];
    DataPickerView(context, items, onSubmitListener: (p1, p2, p3) {
      var item = items[p1];
      timeRange = item.pickId??"";
      timeRangeName = item.pickName??"";
      notifyListeners();
    }).show();
  }

  List<FoodMenuList> foodList = [];
  List<FoodMenuList> selectFoodList = [];

  Future<void> getFoodMenu() async {
    showLoadingDialog();
    try {
      var map = await PostRequest.getFoodMenu();
      hideDialog();
      var bean = ResponseData<FoodMenuList>.fromJson(map,
          listBuilder: (i) => FoodMenuList.fromJson(i));
      if ("0" == bean.code) {
        foodList = bean.data?.rows??[];
        notifyListeners();
      } else {
        showToast(bean.msg??"");
      }
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  String get selectFood =>
      selectFoodList.map((e) => e.bean?.name??"").toList().join("、");

  List<Widget> get foodWidgets => foodList.map((e) {
        return Column(
          children: [
            ImageLoad(
              '${HttpApi.imageHead}${e.bean?.fileId}',
              placeholder: 'assets/none.png',
              errorImage: 'assets/none.png',
              width: double.infinity,
              fit: BoxFit.cover,
            ).setWeight(1),
            CommonText(e.bean?.name??"",
                textColor: selectFoodList.contains(e)
                    ? Colors.white
                    : Color(0xff666666))
          ],
        ).addToContainer(
          padding: EdgeInsets.only(top: 8,right: 8,left: 8),
          decoration: BoxDecoration(
            color: selectFoodList.contains(e)?Colours.app_main:Colors.white
          )
        ).onTap(() {
          if (selectFoodList.contains(e)) {
            selectFoodList.remove(e);
          } else {
            selectFoodList.add(e);
          }
          notifyListeners();
        });
      }).toList();

  @override
  void onCreated() {
    super.onCreated();
    getFoodMenu();
  }

  Future<void> submitMeal() async {
    if (older == null) {
      showToast("请选择长者");
      return;
    }

    if (mealTime.isEmpty) {
      showToast("请选择用餐时间");
      return;
    }

    if (timeRange.isEmpty) {
      showToast("请选择用餐时段");
      return;
    }

    if (selectFood.isEmpty) {
      showToast("请先选择菜品");
      return;
    }

    List<Map<String, dynamic>> details = selectFoodList.map((e) {
      return {"menuId": e.bean!.id, "count": 1};
    }).toList();

    showLoadingDialog(msg: "提交中...");
    try {
      var map = await PostRequest.submitFood(
          older!.id.toString(), mealTime, timeRange, details);
      var bean = ResponseData.fromJson(map);
      if ("0" == bean.code) {
        showToast("提交成功");
        sendMessage(SendMessageEvent(MessageConfig.FINISH_MEAL_SIGN));
        finish();
      } else {
        showToast(bean.msg??"");
      }
      hideDialog();
    } catch (e) {
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }
}
